var cordova = require('cordova');
var exec = require('cordova/exec');
//    var channel = require('cordova/channel');

/**
 * 通过 addDocumentEventHandler 或者 addStickyDocumentEventHandler 或者 addWindowEventHandler 创建事件通道，
 * 并通过 fireDocumentEvent 或者 fireWindowEvent 发布事件消息，
 * 这样我们就可以通过 document.addEventListener 或者 window.addEventListener 订阅监听事件了。
 */
var Rfid = function () {
    this.channels = null;
    var me = this;
    me.channels = {
        rfidstartinventory6c: cordova.addDocumentEventHandler('rfidstartinventory6c')
    };
    for (var key in me.channels) {
        me.channels[key].onHasSubscribersChange = Rfid.onHasSubscribersChange;
    }
//        channel.onDeviceReady.subscribe(function () {
//            // Create new event handlers on the window (returns a channel instance)
//            me.channels = {
//                rfidstartinventory6c: cordova.addWindowEventHandler('rfidstartinventory6c')
//            };
//            for (var key in me.channels) {
//                me.channels[key].onHasSubscribersChange = Rfid.onHasSubscribersChange;
//            }
//        });
};

function numHandlers() {
    return rfid.channels['rfidstartinventory6c'].numHandlers
}

/**
 * Event handlers for when callbacks get registered for the Rfid.
 * Keep track of how many handlers we have so we can start and stop the native battery listener
 * appropriately (and hopefully save on battery life!).
 */
Rfid.onHasSubscribersChange = function () {
    // If we just registered the first handler, make sure native listener is started.
    // console.log(this.numHandlers)
    // console.log(numHandlers())
    if (this.numHandlers === 1 && numHandlers() === 1) {
        exec(
            rfid._startInventory6cSuccess,
            rfid._startInventory6cError,
            'Rfid',
            'inventory_6c_listener',
            [true]
        );
    } else if (numHandlers() === 0) {
        //       exec(null, null, 'Rfid', 'stop_inventory_6c', [false]);
    }
};

Rfid.prototype.getDevices = function ({
    args,
    success,
    error
}) {
    exec(
        success && function (message) { // 成功回调function
            success(message);
        },
        error && function (errorMessage) { // 失败回调function
            error(errorMessage);
        },
        "Rfid", //service feature name
        "get_devices", // action
        args || [] // 要传递的参数，json格式
    );
};

Rfid.prototype.connectRs232 = function ({
    args,
    success,
    error
}) {
    exec(
        success && function (message) { // 成功回调function
            success(message);
        },
        error && function (errorMessage) { // 失败回调function
            error(errorMessage);
        },
        "Rfid", // feature name
        "connect_rs232", // action
        args || [] // 要传递的参数，json格式
    );
};

Rfid.prototype.disConnect = function ({
    success,
    error
}) {
    exec(
        success && function (message) { // 成功回调function
            success(message);
        },
        error && function (errorMessage) { // 失败回调function
            error(errorMessage);
        },
        "Rfid", // feature name
        "disConnect", // action
        [] // 要传递的参数，json格式
    );
};

Rfid.prototype.refresh = function ({
    success,
    error
}) {
    exec(
        success && function (message) { // 成功回调function
            success(message);
        },
        error && function (errorMessage) { // 失败回调function
            error(errorMessage);
        },
        "Rfid", // feature name
        "refresh", // action
        [0, '6C'] // 0: 盘存标签, 6C: 标签类型 6C
    );
};

Rfid.prototype.startInventory6c = function ({
    args,
    success,
    error
}) {
    // If we just registered the first handler, make sure native listener is started.
    exec(
        success && function (message) { // 成功回调function
            success(message);
        },
        error && function (errorMessage) { // 失败回调function
            error(errorMessage);
        },
        'Rfid',
        'start_inventory_6c',
        [true]
    );
};

/**
 * Callback for battery status
 *
 * @param {Object} info {}
 */
Rfid.prototype._startInventory6cSuccess = function (info) {
    if (info) {
        // Something changed. Fire inventory6cData event
        cordova.fireDocumentEvent('rfidstartinventory6c', {data: info});
    }
};

Rfid.prototype._startInventory6cError = function (e) {
    console.log('Rfid Error: start inventory 6c : ' + e);
};

Rfid.prototype.stopInventory6c = function ({
    args,
    success,
    error
}) {
    // If we just registered the first handler, make sure native listener is started.
    exec(
        success && function (message) { // 成功回调function
            success(message);
        },
        error && function (errorMessage) { // 失败回调function
            error(errorMessage);
        },
        'Rfid',
        'stop_inventory_6c',
        [false]
    );
};

/**
 * Error callback for Rfid start
 */
Rfid.prototype._error = function (e) {
    console.log('Error initializing Rfid: ' + e);
};

var rfid = new Rfid();

module.exports = rfid;